#!/usr/bin/env python

import json
from entry import save_payload, create_inputs
import sys
import encrypted_packet_type_b_pynacl as packet_type_b


def main():
	if len(sys.argv) < 2:
		filename = "response"
	else:
		filename = sys.argv[1]

	# load config files
	config = json.load(open("build/config.json", 'r'))
	keys = json.load(open("build/client_key.json", 'r'))

	inputs = create_inputs(config)
	count = 0

	for input in inputs:
		print("Checking %s" % input.name)
		while True:
			payload = input.get_payload("output_box")
			if payload is None:
				break
			try:
				payload = packet_type_b.verify_encrypted_packet(keys, payload)
			except Exception as e:
				print "Failed to decrypt message: ", e
			else:
				count += 1
				ret = save_payload(payload, filename + ("%03d" % count))
				print "Saved to %s" % ret


if __name__ == '__main__':
	main()
